package com.dc.mqtt;

import com.alibaba.fastjson.JSON;
import com.dc.factory.DeviceFactory;
import com.dc.ro.CommonParams;
import com.dc.service.DeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.MessageHandler;

import java.util.Objects;

import static com.dc.mqtt.MqttConfig.INPUT_CHANNEL;

/**
 * mqtt队列监听类
 */
@Slf4j
@Configuration
public class mqttHandler {
    //通过通道获取数据
    @Bean
    @ServiceActivator(inputChannel = INPUT_CHANNEL)
    public MessageHandler handler() {
        return message -> {
            try {
                String topic = Objects.requireNonNull(message.getHeaders().get("mqtt_receivedTopic")).toString();
                String mqttId = Objects.requireNonNull(message.getHeaders().getId()).toString();
                String serviceId = topic.substring(topic.lastIndexOf("/") + 1);
                String payLoad = message.getPayload().toString();
                log.info("当前主题=======>:{}", topic);
                log.info("消息id=======>:{}", mqttId);
                log.info("payLoad=======>:{}", payLoad);
                CommonParams commonParams = JSON.parseObject(payLoad, CommonParams.class);
                // 收到mqtt消息,调用netty下发指令
                DeviceService strategy = DeviceFactory.getStrategy(serviceId);
                if (null != strategy) {
                    strategy.deviceHandler(payLoad, mqttId, commonParams);
                }
            } catch (Exception exception) {
                // 有可能serviceId为空 有可能serviceId不对拿不到handler
                log.error("处理失败", exception);
            }
        };
    }
}
